#include "Enemy.h"

const char Enemy::className[] = "Enemy";

#define method(class, name) {#name, &class::name}

Lunar<Enemy>::RegType Enemy::methods[] = {
	method(Enemy, spot),
	method(Enemy, load),
};

void Enemy::update() {
	Character::update();

	double x1 = m_ptransform->getPosition()[0];
	double y1 = m_ptransform->getPosition()[1];
	double x2 = StageManager::getInstance().getCurrentStage()->getPlayer()->getPosition()[0];
	double y2 = StageManager::getInstance().getCurrentStage()->getPlayer()->getPosition()[1];

	double distance = sqrt(pow((x2-x1),2)+pow((y2-y1),2));

	double xD = x2 - x1;
	double yD = y2 - y1;
	double norme = sqrt( pow(xD,2) + pow(yD,2) );
	xD /= norme;
	yD /= norme;

	float angle = abs(acos(xD) - acos(m_pbrain->getDirection()[0]));
	if((angle <= m_dfieldOfVision) && (distance <= m_drange)) {
		//Check if the player is hidden
		if (!StageManager::getInstance().getCurrentStage()->getPlayer()->isHidded()){
			// Update suspicion gauge
			StageManager::getInstance().getCurrentStage()->getHud()->setJaugeLevel(0.005);
		}
	}

}

int Enemy::load(lua_State* L) {
	Character::load(L);

	osg::Geometry* geom = new osg::Geometry;

	// Position du rectangle
    osg::Vec3Array* radar = new osg::Vec3Array;
	osg::Vec3d pos = osg::Vec3d(0.0,0.0,0.0);
    radar->push_back(pos);

	for(double d = -FIELD/2.; d<FIELD/2.; d+= 0.1) {
		radar->push_back(osg::Vec3d(sin(d)*RANGE, cos(d)*RANGE, 0.0));
	} 

    geom->setVertexArray(radar);
 
	// Couleur du radar
    osg::Vec4Array* colors = new osg::Vec4Array;
	colors->push_back(osg::Vec4d(1.0, 0.0, 0.0, 0.5));
    geom->setColorArray(colors);
    geom->setColorBinding(osg::Geometry::BIND_OVERALL);

	geom->addPrimitiveSet(new osg::DrawArrays(GL_TRIANGLE_FAN,0,radar->size()));

    osg::StateSet* stateset = geom->getOrCreateStateSet();
    stateset->setMode(GL_BLEND,osg::StateAttribute::ON);
    stateset->setAttribute(new osg::PolygonOffset(1.0f,1.0f),osg::StateAttribute::ON);
    stateset->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);

	osg::Geode* geode = new osg::Geode;
	geode->addDrawable(geom);

	m_ptransform->addChild(geode);

	return 0;
}

int Enemy::spot(lua_State* L) {
	return 0;
}
